//
//  MusicHallController.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/10/31.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "MusicHallController.h"
#import "SingerListController.h"
#import "MusicCategoryController.h"
#import "AlbumViewController.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "XCWaterFallLayout.h"
#import "SongCategoryView.h"
#import "FocusPicBLL.h"
#import "MusicHallBLL.h"
#import "GeDanHeaderView.h"
#import "GeDanCollectionViewCell.h"

//@"新歌速递":@"热门歌单";
#define kNewestSongTitle @"新歌速递"
#define kHotSongTitle @"热门歌单"
#define kMusicHeaderViewHeight 40.0f

@interface MusicHallController ()<SDCycleScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate> {

    NSMutableArray *_musicTitles;
}
@property (nonatomic,strong) FocusPicBLL *focusBLL;
@property (nonatomic,strong) MusicHallBLL *hallBLL;
@property (nonatomic,strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic,strong) UIScrollView *containerView;
@property (nonatomic,strong) SongCategoryView *songCategoryView;
@property (nonatomic,strong) UICollectionView *musicCollectionView;
@property (nonatomic,strong) NSMutableDictionary *sourceMusics;
@end

@implementation MusicHallController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title =@"音乐馆";
    self.view.backgroundColor=[UIColor redColor];
    
    [self.view addSubview:self.containerView];
    // 网络加载图片的轮播器
    [self.containerView addSubview:self.cycleScrollView];
    //加载图片的轮播
    __weak FocusPicBLL *WSELF=self.focusBLL;
    [self.focusBLL loadFocus:^{
        _cycleScrollView.titlesGroup = WSELF.titles;
        _cycleScrollView.imageURLStringsGroup = WSELF.imageURLs;
    }];
    
    
    [self.containerView addSubview:self.songCategoryView];
    [self.containerView addSubview:self.musicCollectionView];
    
    __weak MusicHallBLL *_hall=self.hallBLL;
    [self.hallBLL loadCompletion:^{
        
        [_musicTitles removeAllObjects];
        
        if([_hall.newestSongList count]>0){
            [self.sourceMusics setValue:_hall.newestSongList forKey:kNewestSongTitle];
            [_musicTitles addObject:kNewestSongTitle];
        }else{
            [self.sourceMusics removeObjectForKey:kNewestSongTitle];
        }
        if([_hall.hotGeDanList count]>0){
            [self.sourceMusics setValue:_hall.hotGeDanList forKey:kHotSongTitle];
            [_musicTitles addObject:kHotSongTitle];
        }else{
            [self.sourceMusics removeObjectForKey:kHotSongTitle];
        }
        [self layoutCollectionView];
        [self.musicCollectionView reloadData];
    }];
    [self.hallBLL getDataBack];
    
    
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    //[self.cycleScrollView adjustWhenControllerViewWillAppera];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -private
- (void)layoutCollectionView{
    
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.musicCollectionView.collectionViewLayout;

    __block CGFloat height = 0.0f;
    [_musicTitles enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
        height += kMusicHeaderViewHeight;
        
        NSInteger total = [[self.sourceMusics objectForKey:key] count] % 3 == 0? ([[self.sourceMusics objectForKey:key] count] /3) : ([[self.sourceMusics objectForKey:key] count] / 3 +1);
        
        height += total * layout.itemSize.height + (total -1) *layout.minimumLineSpacing + layout.sectionInset.top + layout.sectionInset.bottom;
    }];
    
    CGRect r = self.musicCollectionView.frame;
    r.size.height = height;
    self.musicCollectionView.frame = r;
    
    self.containerView.contentSize = CGSizeMake(self.view.width, CGRectGetMaxY(r));
}

#pragma mark -懒加载
- (FocusPicBLL *)focusBLL{
    if (!_focusBLL) {
        _focusBLL=[[FocusPicBLL alloc] init];
    }
    return _focusBLL;
}

- (MusicHallBLL *)hallBLL{
    if (!_hallBLL) {
        _hallBLL=[[MusicHallBLL alloc] init];
    }
    return _hallBLL;
}

- (UIScrollView *)containerView{
    if (!_containerView) {
        _containerView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-NAV_VIEW_HEIGHT-49)];
        _containerView.pagingEnabled=YES;
        _containerView.contentSize = CGSizeMake(self.view.width, 1200);
    }
    return _containerView;
}

- (SDCycleScrollView *)cycleScrollView{

    if (!_cycleScrollView) {
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 150) delegate:self placeholderImage:nil];
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    }
    return _cycleScrollView;
}

- (SongCategoryView *)songCategoryView{
    if (!_songCategoryView) {
        _songCategoryView=[SongCategoryView instancetypeSongCategoryViewOffsetY:CGRectGetMaxY(self.cycleScrollView.frame)];
        __weak MusicHallController *WSELFMusicHall=self;
        [_songCategoryView setSongCategoryFinishedClick:^(SongCategoryFunction functionType) {
            if (functionType == SongCategoryFunctionArt) {
                SingerListController *singer=[[SingerListController alloc] init];
                [WSELFMusicHall.navigationController pushViewController:singer animated:YES];
            }else if (functionType == SongCategoryFunctionType){
            
                MusicCategoryController *musicCategory = [[MusicCategoryController alloc] init];
                [WSELFMusicHall.navigationController pushViewController:musicCategory animated:YES];
            }else if (functionType == SongCategoryFunctionAlbum){
            
                AlbumViewController *album = [[AlbumViewController alloc] init];
                [WSELFMusicHall.navigationController pushViewController:album animated:YES];
            }
        }];
    }
    return _songCategoryView;
}

- (UICollectionView *)musicCollectionView{

    if (!_musicCollectionView) {
     
        UICollectionViewFlowLayout *flowlayOut = [[UICollectionViewFlowLayout alloc] init];
        flowlayOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        flowlayOut.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowlayOut.minimumLineSpacing = 10; //行间距
        flowlayOut.minimumInteritemSpacing = 10;//列间距
        
        CGFloat width= (self.view.width - flowlayOut.sectionInset.left - flowlayOut.sectionInset.right -flowlayOut.minimumInteritemSpacing * 2)/3;
        flowlayOut.itemSize = CGSizeMake(width, 111);

        _musicCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.songCategoryView.frame), self.view.width,60+111*4) collectionViewLayout:flowlayOut];
        _musicCollectionView.dataSource = self;
        _musicCollectionView.delegate = self;
        _musicCollectionView.backgroundColor = [UIColor whiteColor];
        [_musicCollectionView registerClass:[GeDanCollectionViewCell class] forCellWithReuseIdentifier:kNewstCollectionViewCellIdentifier];
        [_musicCollectionView registerClass:[GeDanCollectionViewCell class] forCellWithReuseIdentifier:kHotGeDanCollectionViewCellIdentifier];
        [_musicCollectionView registerClass:[GeDanHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kGeDanHeaderViewIdentifier];
        
        DLog(@"frame = %@",NSStringFromCGRect(_musicCollectionView.frame));
    }
    return _musicCollectionView;
}

- (NSMutableDictionary *)sourceMusics{

    if (!_sourceMusics) {
        _sourceMusics = [[NSMutableDictionary alloc] initWithCapacity:0];
        _musicTitles =[[NSMutableArray alloc] initWithCapacity:0];
    }
    return _sourceMusics;
}

#pragma mark - SDCycleScrollViewDelegate Methods
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
}


#pragma mark - UICollectionViewDataSource Methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [_musicTitles count];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSString *key = [_musicTitles objectAtIndex:section];
    return [[self.sourceMusics objectForKey:key] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //DLog(@"cellForItemAtIndexPath section =%d ,row =%d",indexPath.section,indexPath.row);
    
    NSString *key = [_musicTitles objectAtIndex:indexPath.section];
    NSArray *source = [self.sourceMusics objectForKey:key];
    
    
    GeDanCollectionViewCell *cell=nil;
    if ([source[indexPath.row] isKindOfClass:[NewestBillboard class]]) {
        
        cell=[collectionView dequeueReusableCellWithReuseIdentifier:kNewstCollectionViewCellIdentifier forIndexPath:indexPath];
        
        NewestBillboard *item = source[indexPath.row];
        
        cell.titleLabel.text = item.album_title;
        [cell.focusImageView sd_setImageWithURL:[NSURL URLWithString:item.pic_small] placeholderImage:nil];
    }else{
        cell=[collectionView dequeueReusableCellWithReuseIdentifier:kHotGeDanCollectionViewCellIdentifier forIndexPath:indexPath];
        HotGeDan *item = source[indexPath.row];
        
        cell.titleLabel.text = item.title;
        [cell.focusImageView sd_setImageWithURL:[NSURL URLWithString:item.pic] placeholderImage:nil];
    }
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"layoutAttributesForDecorationViewOfKind section =%d ,row =%d",indexPath.section,indexPath.row);
    //DLog(@"kind = %@ ,section =%d ,row =%d", kind,indexPath.section,indexPath.row);
    if (kind == UICollectionElementKindSectionHeader){
        
        GeDanHeaderView *headerV = (GeDanHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kGeDanHeaderViewIdentifier forIndexPath:indexPath];
        headerV.titleLabel.text = [_musicTitles objectAtIndex:indexPath.section];
       
        return headerV;
    }
    
    return nil;
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.width, kMusicHeaderViewHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
